const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {
            nickName: '点击登录',
            avatarUrl: '/static/images/my.png'
        },
        hasLogin: false,
        collectList: [],
        activeNames: [],
        showRemarkPop: false,
        recordId: '',
        points: 0,
        dataUrl: '',
        k: false,
        showStrategyApplication: false,
        strategyRemark: "",
        reward: 88.88,
        runType: 1,
        strategyContext: "",
        strategyName: "",
        wxId: "",
        strategyAutoSize: {
            maxHeight: 50,
            minHeight: 100
        },

        recordId:'',
        remark:'',
        optype:'add',
        opindex:'0',
        remarkContext: '',
        autoSize: {
            maxHeight: 800,
            minHeight: 200
        },
    },

    onChouseRuntype(event) {
        this.setData({
            runType: event.detail
        })
    },
    strategyApplication() {
        util.request(api.StrategyApplication, {
            "remark": this.data.strategyRemark,
            "reward": this.data.reward,
            "runType": this.data.runType,
            "strategyContext": this.data.strategyContext,
            "strategyName": this.data.strategyName,
            "wxId": this.data.wxId
        }, "POST").then(res => {
            if (res.success) {
                wx.showToast({
                    title: '提交成功',
                    icon: 'none'
                })
                this.setData({
                    showStrategyApplication: false,
                    showRemarkPop:false,
                    strategyContext: "",
                    strategyName: "",
                    wxId: "",
                    strategyRemark: "",
                    reward: 88.88,
                    runType: 1,
                })
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none'
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getTabBar().init();
        this.getTabBar().setCartNumber(wx.getStorageSync('collectStrategy').length)
        //获取用户的登录信息
        if (app.globalData.hasLogin) {
            let k = wx.getStorageSync('k');
            let userInfo = wx.getStorageSync('userInfo');
            console.log(userInfo, 'userInfo')
            this.setData({
                k: k,
                userInfo: userInfo,
                hasLogin: true
            });

            util.request(api.UserInfo).then(resp => {
                if (resp.success && resp.data.points != null) {
                    this.setData({
                        points: resp.data.points
                    })
                }
            })

            let that = this;
            util.request(api.CollectStocks).then(resp => {
                this.setData({
                    collectList: resp.data.map(item => {
                        item.latest = parseFloat(item.latest)
                        item.collectPrice = parseFloat(item.collectPrice)
                        item.imgType = 'daily'
                        let isSH = item.stockCode.substr(0, 2) == '60' || item.stockCode.substr(0, 2) == '68'
                        let tempUrl = `http://image.sinajs.cn/newchart/daily/n/${isSH ? 'sh' : 'sz'}${item.stockCode}.gif`
                        item.dataUrl = tempUrl
                        return item
                    })
                })
            })

        }
    },

    goLogin() {
        if (!this.data.hasLogin) {
            wx.navigateTo({
                url: "/pages/auth/login/login"
            });
        }
    },
    showStrategyApplication() {
        this.setData({
            showStrategyApplication: true
        })
    },
    onClose() {
        this.setData({
            showStrategyApplication: false,
            showRemarkPop:false
        })
    },
    exitLogin: function () {
        wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            content: '退出登录？',
            success: function (res) {
                if (!res.confirm) {
                    return;
                }

                util.request(api.AuthLogout, {}, 'POST');
                app.globalData.hasLogin = false;
                wx.removeStorageSync('token');
                wx.removeStorageSync('userInfo');
                util.request(api.StrategyList).then(resp => {

                    let data = resp.data.map(x => {
                        return {
                            id: x.id,
                            text: x.strategyName
                        }
                    })
                    wx.setStorageSync('collectStrategy', data)
                    this.getTabBar().setCartNumber(data.length)
                })
                wx.reLaunch({
                    url: '/pages/index/index'
                });
            }
        })

    },
    showRemarkPop(event) {
        console.log('展示备注');
        let {
            index,
            optype,
        } = event.target.dataset
        let tempJson = this.data.collectList[index]
        this.setData({
            recordId: tempJson.id,
            remark: tempJson.remark,
            optype,
            opindex: index,
            showRemarkPop: true
        })
    },
    updateRemark(data) {
        // let detail = data.detail
        let collectList = this.data.collectList
        let tempJson = collectList[data.index]
        tempJson.remark = data.remark
        this.setData({
            collectList
        })
    },
    cancelCollect(event) {
        let {
            index,
        } = event.target.dataset
        let _this = this
        let collectList = this.data.collectList
        wx.showModal({
            title: '提示',
            content: '是否取消收藏该记录?',
            success(res) {
                if (res.confirm) {
                    util.request(api.CancleCollectStock, {
                        "stockCode": collectList[index].stockCode
                    }).then(resp => {
                        if (resp.success) {
                            collectList.splice(index, 1)
                            _this.setData({
                                collectList
                            }, () => {
                                wx.showToast({
                                    title: '取消成功',
                                })
                            })
                        }
                    })
                }
            }
        })
    },

    accountLogin: function () {
        wx.navigateTo({
            url: "/pages/auth/accountLogin/accountLogin"
        });
    },

    newLoginApi() {
        if (!app.globalData.hasLogin) {
            wx.getUserProfile({
                desc: '获取你的昵称、头像、地区及性别',
                success: e => {
                    console.log('用户信息:', e)
                    user.loginByWeixin(e.userInfo).then(res => {
                        app.globalData.hasLogin = true;
                        wx.navigateBack({
                            delta: 1
                        })
                        util.request(api.StrategyList).then(resp => {
                            console.log('登录后获取的策略值', resp)
                            let data = resp.data.map(x => {
                                return {
                                    id: x.id,
                                    text: x.strategyName
                                }
                            })
                            wx.setStorageSync('collectStrategy', data)
                            this.getTabBar().setCartNumber(data.length)
                        })
                    }).catch((err) => {
                        app.globalData.hasLogin = false;
                        util.showErrorToast('微信登录失败');
                    });
                }
            })
        }

    },

    onChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },

    /**
     * 切换图片
     */
    toggleImg(event) {
        let {
            index,
            type
        } = event.target.dataset
        let {
            collectList
        } = this.data
        console.log(event, "--- event");
        let tempJson = collectList[index]
        let isSH = tempJson.stockCode.substr(0, 2) == '60' || tempJson.stockCode.substr(0, 2) == '68'
        let tempUrl = `http://image.sinajs.cn/newchart/${type}/n/${isSH ? 'sh' : 'sz'}${tempJson.stockCode}.gif`
        tempJson.dataUrl = tempUrl
        tempJson.imgType = type
        this.setData({
            collectList
        })
    },

    /**预览图片 */
    prviewImg(event) {
        let {
            dataurl,
        } = event.target.dataset
        wx.previewImage({
            urls: [dataurl],
            current: 'current',
            showmenu: true
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    hidePop() {
        this.setData({
            showRemarkPop: false,
            remarkContext: '',
            recordId: '',
        })
    },
    stockRemark() {
        let _this = this
        let {
            remarkContext,
            optype,
            remark,
            opindex,
            recordId
        } = _this.data
        if(!remarkContext && !remark){
            wx.showToast({
              title: '备注不能为空',
              icon:'none'
            })
            return
        }
        util.request(api.RemarkStocks, {
            "recordId": recordId,
            "remarkContext": optype == 'add' ? remarkContext : remark,
        }).then(resp => {
            if (resp.success) {
                wx.showToast({
                    title: optype == 'add' ? '备注添加成功' : '备注修改成功',
                })
                _this.setData({
                    showRemarkPop: false,
                    remarkContext: '',
                    recordId: '',
                })
                if (optype == 'edit') {
                    this.updateRemark({remark:remark,index:opindex})
                }

            } else {
                wx.showToast({
                    title: resp.message,
                    icon: 'none'
                })
            }
        })
    }
})